import { Injectable } from '@angular/core';
import { AppConfig } from "../config";
import { Http, Headers } from "@angular/http";
import { UserFarmAlarmconfig } from "../entity/user_farm_alarmconfig.model";
import { InterceptorService } from '../service/interceptor/interceptor-service';

@Injectable()
export class UserFarmAlarmconfigService {
    private readonly param = "userFarmAlarmconfigs";
    private get url(): string {
        return `${AppConfig.APP_RESTFUL}/${this.param}`;
    }

    constructor(private http: InterceptorService) { }

    /**
     * 获得用户风场报警配置集合
     * 
     * @returns {Promise<UserFarmAlarmconfig[]>} 
     * @memberof UserFarmAlarmconfigService
     */
    getUserFarmAlarmconfigs(): Promise<UserFarmAlarmconfig[]> {
        return this.http.get(this.url)
            .toPromise()
            .then(response => response.json().data as UserFarmAlarmconfig[])
            .catch(this.handleError);
    }

    /**
     * 根据用户Id获得用户风场报警配置集合
     * 
     * @param {number} userId 
     * @returns {Promise<UserFarmAlarmconfig[]>} 
     * @memberof UserFarmAlarmconfigService
     */
    getUserFarmAlarmconfigsByUserId(userId: number): Promise<UserFarmAlarmconfig[]> {
        return this.http.get(`${AppConfig.APP_RESTFUL}/UFAlarmConfigs/user/${userId}`)
            .toPromise()
            .then(response => response.json().data as UserFarmAlarmconfig[])
            .catch(this.handleError);

    }

    update(userFarmAlarm: UserFarmAlarmconfig): Promise<UserFarmAlarmconfig> {
        const url = `${this.url}`;
        return this.http.put(`${AppConfig.APP_RESTFUL}/UFAlarmConfigs`, JSON.stringify(userFarmAlarm))
            .toPromise()
            .then(() => userFarmAlarm)
            .catch(this.handleError);

        // return this.http.post(url, JSON.stringify(userFarmAlarm), { headers: this.headers })
        //     .toPromise()
        //     .then(res => {
        //         try {
        //             let result = res.json();
        //             switch (result.code) {
        //                 case "200":
        //                     return result.data as UserFarmAlarmconfig;
        //                 case "-1":
        //                     throw new Error(result.message);
        //             }
        //         }
        //         catch (error) {
        //             this.handleError(error);
        //         }
        //     })
        //     .catch(this.handleError);
    }

    private handleError(error: any): Promise<any> {
        // console.error('An error occurred', error); // for demo purposes only
        return Promise.reject(error.message || error);
    }

}


// WEBPACK FOOTER //
// ./src/app/service/user-farm-alarmconfig.service.ts